package cn.stylefeng.guns.modular.basic.service.impl;

import cn.stylefeng.guns.base.pojo.page.LayuiPageFactory;
import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.core.util.ExcelWrite;
import cn.stylefeng.guns.modular.basic.entity.BasicGoods;
import cn.stylefeng.guns.modular.basic.mapper.BasicGoodsMapper;
import cn.stylefeng.guns.modular.basic.model.params.BasicGoodsParam;
import cn.stylefeng.guns.modular.basic.model.result.BasicGoodsResult;
import cn.stylefeng.guns.modular.basic.service.BasicGoodsService;
import cn.stylefeng.guns.modular.order.entity.OrderPutExcelItem;
import cn.stylefeng.guns.modular.replenishment.model.result.BHStorageStockResult;
import cn.stylefeng.guns.modular.storage.model.params.StorageStockParam;
import cn.stylefeng.guns.modular.storage.service.StorageStockService;
import cn.stylefeng.guns.modular.tool.model.params.ToolExpressReconciliationJtParam;
import cn.stylefeng.guns.modular.tool.model.result.ToolExpressReconciliationJtResult;
import cn.stylefeng.guns.sys.modular.system.entity.User;
import cn.stylefeng.guns.sys.modular.system.service.UserService;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

/**
 * 商品表 服务实现类
 */
@Service
public class BasicGoodsServiceImpl extends ServiceImpl<BasicGoodsMapper, BasicGoods> implements BasicGoodsService {

    @Override
    public void add(BasicGoodsParam param){
        BasicGoods entity = getEntity(param);
        this.save(entity);
    }

    @Override
    public void delete(BasicGoodsParam param){
        this.removeById(getKey(param));
    }

    @Override
    public void update(BasicGoodsParam param){
        BasicGoods oldEntity = getOldEntity(param);
        BasicGoods newEntity = getEntity(param);
        ToolUtil.copyProperties(newEntity, oldEntity);
        this.updateById(newEntity);
    }

    @Override
    public BasicGoodsResult findBySpec(BasicGoodsParam param,Long operateId){
        return this.baseMapper.findBySpec(param,operateId);
    }


    @Override
    public LayuiPageInfo findPageBySpec(BasicGoodsParam param,String condition,Long deptId, Long operateId){
        Page pageContext = getPageContext();
        IPage page = this.baseMapper.customPageList(pageContext, param,condition,deptId, operateId);
        return LayuiPageFactory.createPageInfo(page);
    }

    @Override
    public List<BasicGoodsResult> findListBySpec(BasicGoodsParam basicGoodsParam, Long operateId) {
        return this.baseMapper.findListBySpec(basicGoodsParam, operateId);
    }

    @Override
    public List<BasicGoodsResult> findListBySpecNew(BasicGoodsParam basicGoodsParam, Long deptId,String condition,Long operateId) {
        return this.baseMapper.findListBySpecNew(basicGoodsParam, deptId,condition,operateId);
    }

    private Serializable getKey(BasicGoodsParam param){
        return param.getId();
    }

    private Page getPageContext() {
        return LayuiPageFactory.defaultPage();
    }

    private BasicGoods getOldEntity(BasicGoodsParam param) {
        return this.getById(getKey(param));
    }

    private BasicGoods getEntity(BasicGoodsParam param) {
        BasicGoods entity = new BasicGoods();
        ToolUtil.copyProperties(param, entity);
        return entity;
    }

	private static String getCellValue(Cell cell) {
        if (cell == null) {
            return "";
        }
        if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
            if (DateUtil.isCellDateFormatted(cell)) {
                return HSSFDateUtil.getJavaDate(cell.getNumericCellValue()).toString();
            } else {
                return new BigDecimal(cell.getNumericCellValue()).toString();
            }
        } else if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
            return StringUtils.trimToEmpty(cell.getStringCellValue());
        } else if (cell.getCellType() == Cell.CELL_TYPE_FORMULA) {
            return StringUtils.trimToEmpty(cell.getCellFormula());
        } else if (cell.getCellType() == Cell.CELL_TYPE_BLANK) {
            return "";
        } else if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
            return String.valueOf(cell.getBooleanCellValue());
        } else if (cell.getCellType() == Cell.CELL_TYPE_ERROR) {
            return "ERROR";
        } else {
            return cell.toString().trim();
        }
    }

	@Override
	@Transactional(rollbackFor = Exception.class,timeout=150)
	public ResponseData getExceldata(MultipartFile file, BasicGoodsParam basicGoodsParam, ResponseData data) throws Exception {
		if (ToolUtil.isEmpty(basicGoodsParam.getGoodsCustomerId()) || ToolUtil.isEmpty(basicGoodsParam.getGoodsCustomerName())) {
			data.setSuccess(false);
			data.setMessage("Please select a customer");
			return data;
		}

		String fileName = file.getOriginalFilename();
		List<BasicGoodsParam> list = new ArrayList<BasicGoodsParam>();

		if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
			data.setMessage("The uploaded file format is incorrect");
			data.setSuccess(false);
        }

		boolean isExcel2003 = true;
        if (fileName.matches("^.+\\.(?i)(xlsx)$")) {
            isExcel2003 = false;
        }
        InputStream is = file.getInputStream();
        Workbook wb = null;
        if (isExcel2003) {
            wb = new HSSFWorkbook(is);
        } else {
            wb = new XSSFWorkbook(is);
        }
        Sheet sheet = wb.getSheetAt(0);

        for (int r = 1; r <= sheet.getLastRowNum()+1; r++) {
        	Row row = sheet.getRow(r);
            if (row == null){
                continue;
            }
            BasicGoodsParam goodsParam = new BasicGoodsParam();
            goodsParam.setDeptId(basicGoodsParam.getDeptId());
            goodsParam.setDeliverId(basicGoodsParam.getDeliverId());
            goodsParam.setGoodsCustomerId(basicGoodsParam.getGoodsCustomerId());
            goodsParam.setGoodsCustomerName(basicGoodsParam.getGoodsCustomerName());
            goodsParam.setCreateTime(new Date());

            String  goodsName = getCellValue(row.getCell(0));
            if (ToolUtil.isNotEmpty(goodsName)) {
            	goodsParam.setGoodsName(goodsName);//商品名称
			}

            String  goodsNumber = getCellValue(row.getCell(1));
            if (ToolUtil.isNotEmpty(goodsNumber)) {
            	BasicGoodsParam param = new BasicGoodsParam();
            	param.setGoodsNumber(goodsNumber);
            	param.setDeliverId(basicGoodsParam.getDeliverId());
            	param.setGoodsCustomerId(basicGoodsParam.getGoodsCustomerId());
            	BasicGoodsResult basicGoodsResult = this.findBySpec(param,null);
            	if (basicGoodsResult == null) {
            		goodsParam.setGoodsNumber(goodsNumber);//商品编号
				} else {
					continue;
				}
			}

            String  goodsNo = getCellValue(row.getCell(2));//货号
            if (ToolUtil.isNotEmpty(goodsNo)) {
            	goodsParam.setGoodsNo(goodsNo);
			}

            String  goodsUnit = getCellValue(row.getCell(3));
            if (ToolUtil.isNotEmpty(goodsUnit)) {
            	goodsParam.setGoodsUnit(goodsUnit);//单位
			}

            String  goodsPacking = getCellValue(row.getCell(4));
            if (ToolUtil.isNotEmpty(goodsPacking)) {
            	goodsParam.setGoodsPacking(goodsPacking);//包装
			}

            String  goodsBigtype = getCellValue(row.getCell(5));
            if (ToolUtil.isNotEmpty(goodsBigtype)) {
            	goodsParam.setGoodsBigtype(goodsBigtype);//大类
			}

            String  goodsType = getCellValue(row.getCell(6));
            if (ToolUtil.isNotEmpty(goodsType)) {
            	goodsParam.setGoodsType(goodsType);//类别
			}

            String  goodsSpecs = getCellValue(row.getCell(7));
            if (ToolUtil.isNotEmpty(goodsSpecs)) {
            	goodsParam.setGoodsSpecs(goodsSpecs);//规格
			}

            String  goodsWarranty = getCellValue(row.getCell(8));
            if (ToolUtil.isNotEmpty(goodsWarranty)) {
            	goodsParam.setGoodsWarranty(goodsWarranty);//保质期
			} else {
            	goodsParam.setGoodsWarranty("36");//保质期
			}

            String  goodsWeight = getCellValue(row.getCell(9));
            if (ToolUtil.isNotEmpty(goodsWeight)) {
            	BigDecimal w = new BigDecimal(goodsWeight).setScale(8,BigDecimal.ROUND_DOWN);
            	goodsParam.setGoodsWeight(w.toString());//重量
			} else {
            	goodsParam.setGoodsWeight("0.1");//重量
			}

            String  goodsVolume = getCellValue(row.getCell(10));
            if (ToolUtil.isNotEmpty(goodsVolume)) {
            	BigDecimal v = new BigDecimal(goodsVolume).setScale(8,BigDecimal.ROUND_DOWN);
            	goodsParam.setGoodsVolume(v.toString());//体积
			} else {
            	goodsParam.setGoodsVolume("0.1");//体积
			}

            String  goodsCharging = getCellValue(row.getCell(11));
            if (ToolUtil.isNotEmpty(goodsCharging)) {
            	BigDecimal p = new BigDecimal(goodsCharging).setScale(3,BigDecimal.ROUND_DOWN);
            	goodsParam.setGoodsCharging(p.toString());//计费指定价
			} else {
            	goodsParam.setGoodsCharging("10");//计费指定价
			}

            String  goodsTraylayer = getCellValue(row.getCell(12));
            if (ToolUtil.isNotEmpty(goodsTraylayer)) {
            	goodsParam.setGoodsTraylayer(goodsTraylayer);//托层
			} else {
            	goodsParam.setGoodsTraylayer("1");//托层
			}

            String  goodsSupportvolume = getCellValue(row.getCell(13));
            if (ToolUtil.isNotEmpty(goodsSupportvolume)) {
            	goodsParam.setGoodsSupportvolume(goodsSupportvolume);//每托存量
			} else {
            	goodsParam.setGoodsSupportvolume("100");//每托存量
			}

            String  goodsBottom = getCellValue(row.getCell(14));
            if (ToolUtil.isNotEmpty(goodsBottom)) {
            	goodsParam.setGoodsBottom(goodsBottom);//底
			} else {
            	goodsParam.setGoodsSupportvolume("10");//底
			}

            String  goodsLamination = getCellValue(row.getCell(15));
            if (ToolUtil.isNotEmpty(goodsLamination)) {
            	goodsParam.setGoodsLamination(goodsLamination);//叠层
			} else {
            	goodsParam.setGoodsLamination("10");//叠层
			}
            list.add(goodsParam);
        }
        if (list.size() > 0) {
        	saveBatchList(list);
		}
        data.setSuccess(true);
		return data;
	}

	@Override
	@Transactional(rollbackFor = Exception.class,timeout=150)
	public ResponseData getExceldataUpadate(MultipartFile file, BasicGoodsParam basicGoodsParam, ResponseData data) throws Exception {
		if (ToolUtil.isEmpty(basicGoodsParam.getGoodsCustomerId()) || ToolUtil.isEmpty(basicGoodsParam.getGoodsCustomerName())) {
			data.setSuccess(false);
			data.setMessage("Please select a customer");
			return data;
		}

		String fileName = file.getOriginalFilename();

		if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
			data.setMessage("The uploaded file format is incorrect");
			data.setSuccess(false);
        }

		boolean isExcel2003 = true;
        if (fileName.matches("^.+\\.(?i)(xlsx)$")) {
            isExcel2003 = false;
        }
        InputStream is = file.getInputStream();
        Workbook wb = null;
        if (isExcel2003) {
            wb = new HSSFWorkbook(is);
        } else {
            wb = new XSSFWorkbook(is);
        }
        Sheet sheet = wb.getSheetAt(0);

        for (int r = 1; r <= sheet.getLastRowNum()+1; r++) {
        	Row row = sheet.getRow(r);
            if (row == null){
                continue;
            }
            BasicGoodsParam goodsParam = new BasicGoodsParam();
            goodsParam.setGoodsCustomerId(basicGoodsParam.getGoodsCustomerId());
        	StorageStockParam storageStockParam = new StorageStockParam();
        	storageStockParam.setCustomerId(Long.parseLong(basicGoodsParam.getGoodsCustomerId().toString()));

            String  goodsName = getCellValue(row.getCell(0));
            if (ToolUtil.isNotEmpty(goodsName)) {
            	goodsParam.setGoodsName(goodsName);//商品名称
            	storageStockParam.setGoodsName(goodsName);
			}

            String  goodsSpecs = getCellValue(row.getCell(7));
            if (ToolUtil.isNotEmpty(goodsSpecs)) {
            	goodsParam.setGoodsSpecs(goodsSpecs);//规格
			}

            String  goodsVolume = getCellValue(row.getCell(10));
            if (ToolUtil.isNotEmpty(goodsVolume)) {
            	BigDecimal v = new BigDecimal(goodsVolume).setScale(8,BigDecimal.ROUND_DOWN);
            	goodsParam.setGoodsVolume(v.toString());
			}

//            String  goodsCharging = getCellValue(row.getCell(2));
//            if (ToolUtil.isNotEmpty(goodsCharging)) {
//            	BigDecimal p = new BigDecimal(goodsCharging).setScale(3,BigDecimal.ROUND_DOWN);
//            	goodsParam.setGoodsCharging(p.toString());//计费指定价
//            	storageStockParam.setUnitprice(p.toString());
//			}

            String  xianggui = getCellValue(row.getCell(16));
            if (ToolUtil.isNotEmpty(xianggui)) {
            	goodsParam.setXianggui(xianggui);
			} else {
				continue;
			}

            String  goodsNumber = getCellValue(row.getCell(1));
            if (ToolUtil.isNotEmpty(goodsNumber)) {
            	goodsParam.setGoodsNumber(goodsNumber);
            	updateBySpec(goodsParam);

            	storageStockParam.setGoodsNumber(goodsNumber);
//            	storageStockService.updateBySpec(storageStockParam);
			} else {
				continue;
			}
        }
        data.setSuccess(true);
		return data;
	}

    @Resource
    private StorageStockService storageStockService;

	@Override
	public boolean saveBatchList(List<BasicGoodsParam> list) {
		return this.baseMapper.saveBatchList(list);
	}

	@Override
	public Integer addReturnId(BasicGoodsParam param) {
		return this.baseMapper.addReturnId(param);
	}

	@Override
	public void updateBySpec(BasicGoodsParam param) {
		this.baseMapper.updateBySpec(param);
	}

    @Resource
    private UserService userService;

	@Override
	public Workbook exportToExcel(BasicGoodsParam basicGoodsParam) {
	    //这是表头
		String[] arr = {"Customer","Commodity Name","Code","Item No.","Mnemonic Code"
				,"Unit","Packaging","Main Category","Category"
				,"Base Layer","Stack Layer","Storage Capacity per Pallet","Pallet Layer"
				,"Weight","Volume","Billing Specified Price"
				,"Specification"
				,"Carton Specification"};
	    //这是具体数据
	    List<List<String>> list = new ArrayList<>();

    	User user = userService.getcurrentUser();
    	basicGoodsParam.setDeptId(user.getDeptId());
	    List<BasicGoodsResult> datalist = this.findListBySpec(basicGoodsParam,user.getOperateId());
	    for (BasicGoodsResult r : datalist) {
		    List<String> list1 = new ArrayList<String>();
		    list1.add(r.getGoodsCustomerName());
		    list1.add(r.getGoodsName());
		    list1.add(r.getGoodsNumber());
		    list1.add(r.getGoodsNo());
		    list1.add(r.getGoodsHelpcode());

		    list1.add(r.getGoodsUnit());
		    list1.add(r.getGoodsPacking());
		    list1.add(r.getGoodsBigtype());
		    list1.add(r.getGoodsType());

		    list1.add(r.getGoodsBottom());
		    list1.add(r.getGoodsLamination());
		    list1.add(r.getGoodsSupportvolume());
		    list1.add(r.getGoodsTraylayer());

		    list1.add(r.getGoodsWeight());
		    list1.add(r.getGoodsVolume());
		    list1.add(r.getGoodsCharging());

		    list1.add(r.getGoodsSpecs());
		    list1.add(r.getXianggui());
		    list.add(list1);
		}
	    return ExcelWrite.writeToExcelByList(arr, list);
	}

	@Override
	public List<BasicGoodsResult> findListBySpecSd(BasicGoodsParam basicGoodsParam) {
		return this.baseMapper.findListBySpecSd(basicGoodsParam);
	}

	@Override
	public List<BHStorageStockResult> findStorageStockByGoodsNumber(String positionType,String goodsNumber, long l) {
		return this.baseMapper.findStorageStockByGoodsNumber(positionType,goodsNumber,l);
	}

	@Override
	public BHStorageStockResult findStorageStockByGoodsNumberNew(String positionType, String detailedGoodsCode, long l) {
		return this.baseMapper.findStorageStockByGoodsNumberNew(positionType,detailedGoodsCode,l);
	}

}
